package com.ub.party.internal.service;

import com.alibaba.fastjson.JSON;
import com.ub.party.common.constants.RespCodeEnum;
import com.ub.party.common.vo.resp.RespVo;
import org.apache.log4j.Logger;

/**
 * 模板方法模式构造TagExecutor
 * Created by HANRAN177 on 2015/8/26.
 */
public abstract class Executor<T> {

  Logger logger = Logger.getLogger(Executor.class);

  private T clazz;

  abstract public boolean validateData(T clazz);

  abstract public String execute(T clazz);

  public RespVo getResult() {
    StackTraceElement[] trace = Thread.currentThread().getStackTrace();
    if (trace.length > 3) {
      logger.info("0. Invoke Method: " + trace[2].getClassName() + "." + trace[2].getMethodName());
    }
    logger.info("1. Request Data: " + JSON.toJSONString(this.getClazz()));
    RespVo respVo = new RespVo();
    if (validateData(this.getClazz())) {
      logger.info("2. Start Execute. ");
      String result = execute(this.getClazz());
      logger.info("3. Execute End. Result - " + result);
      try {
        if (Boolean.TRUE.toString().equals(result)) {
          respVo.setCode(RespCodeEnum.SUCCESS.getCode());
          respVo.setMsg(RespCodeEnum.SUCCESS.getMsg());
        } else {
          respVo.setCode(RespCodeEnum.FAILURE.getCode());
          respVo.setMsg(RespCodeEnum.FAILURE.getMsg());
        }
      } catch (Exception ex) {
        logger.info("5. Execute Throw Exception.  - " + ex.getLocalizedMessage());
//                respVo.setCode(RespCodeEnum.SERVER_EXCEPTION.getCode());
//                respVo.setMsg(RespCodeEnum.SERVER_EXCEPTION.getDesc());
      }
    } else {
      logger.info("6. Data is InValid. ");
      respVo.setCode(RespCodeEnum.DATA_INVALID.getCode());
      respVo.setMsg(RespCodeEnum.DATA_INVALID.getMsg());
    }
    logger.info("4. Response Data: " + JSON.toJSONString(respVo));
    return respVo;
  }

  public T getClazz() {
    return clazz;
  }

  public void setClazz(T clazz) {
    this.clazz = clazz;
  }
}
